import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:provider/provider.dart';
import 'package:sjx/pages/task/task_detail_vm.dart';
import 'package:photo_view/photo_view.dart';
import 'package:photo_view/photo_view_gallery.dart';
import '../../repository/model/task_detail_model.dart';

class TaskDetailPage extends StatefulWidget {
  const TaskDetailPage({super.key, required this.taskId, this.onlyShowDetail});

  final String taskId;
  final bool? onlyShowDetail;

  @override
  State<StatefulWidget> createState() {
    return TaskDetailPageState();
  }
}

class TaskDetailPageState extends State<TaskDetailPage> {
  late final TaskDetailViewModel _viewModel;

  void _actionTask(BuildContext context) {
    _viewModel.actionTask(context);
  }

  @override
  void initState() {
    super.initState();
    _viewModel = TaskDetailViewModel();
    _viewModel.requestTaskDetail(widget.taskId);
  }

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (context) {
        return _viewModel;
      },
      child: Consumer<TaskDetailViewModel>(builder: (context, value, child) {
        final model = value.taskDetailModel ?? TaskDetailViewModel.empty;
        return Scaffold(
          appBar: AppBar(title: const Text('任务详情'), centerTitle: true),
          body: SingleChildScrollView(
            padding: EdgeInsets.all(16.w),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 任务标题和基本信息
                _buildTaskHeader(model),
                SizedBox(height: 16.h),

                // 奖励金额
                _buildRewardSection(model),
                SizedBox(height: 24.h),

                // 发布者信息
                _buildPublisherInfo(model),
                SizedBox(height: 24.h),

                // 任务状态标签
                _buildTaskStatusTags(model),
                SizedBox(height: 24.h),

                // 任务说明
                _buildTaskDescription(model),
                SizedBox(height: 24.h),

                // 任务步骤
                _buildTaskSteps(model),
                SizedBox(height: 24.h),

                // 任务提交内容
                _buildTaskRequirement(model),
                SizedBox(height: 24.h),
              ],
            ),
          ),
          bottomNavigationBar: SafeArea(child: _buildActionButton(model)),
        );
      }),
    );
  }

  Widget _buildTaskHeader(TaskDetailModel model) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          model.taskTitle ?? '无标题',
          style: TextStyle(
            fontSize: 20.sp,
            fontWeight: FontWeight.bold,
            color: Colors.black87,
          ),
        ),
        SizedBox(height: 8.h),
        Row(
          children: [
            Icon(Icons.access_time, size: 16.w, color: Colors.grey),
            SizedBox(width: 4.w),
            Text(
              '任务时间：${model.bidSubmitDurationTimeDisplay ?? ''}',
              style: TextStyle(fontSize: 14.sp, color: Colors.grey),
            ),
            SizedBox(width: 16.w),
            Text(
              '剩余${model.leftBidTime ?? 0}份',
              style: TextStyle(fontSize: 14.sp, color: Colors.orange),
            ),
            Text(
              '·${model.endTimeDisplay ?? ''}',
              style: TextStyle(fontSize: 14.sp, color: Colors.grey),
            ),
          ],
        ),
      ],
    );
  }

  Widget _buildRewardSection(TaskDetailModel model) {
    return Container(
      padding: EdgeInsets.symmetric(vertical: 12.h, horizontal: 16.w),
      decoration: BoxDecoration(
        color: Colors.amber[50],
        borderRadius: BorderRadius.circular(8.r),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            '任务奖励',
            style: TextStyle(fontSize: 16.sp, fontWeight: FontWeight.bold),
          ),
          Text(
            model.rewardAmountDisplay ?? '+0.00元/次',
            style: TextStyle(
              fontSize: 20.sp,
              fontWeight: FontWeight.bold,
              color: Colors.orange,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildPublisherInfo(TaskDetailModel model) {
    return Row(
      children: [
        ClipRRect(
          borderRadius: BorderRadius.all(Radius.circular(8.r)),
          child: CachedNetworkImage(
            fit: BoxFit.cover,
            placeholder: (context, url) {
              return const Center(child: CircularProgressIndicator());
            },
            errorWidget: (context, url, error) {
              return Image.asset(
                'assets/images/header.png',
                width: 48.r,
                height: 48.r,
                fit: BoxFit.cover,
              );
            },
            imageUrl: model.publisherVartar,
            width: 48.r,
            height: 48.r,
          ),
        ),
        SizedBox(width: 12.w),
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              model.publisherName ?? '发布者',
              style: TextStyle(fontSize: 16.sp),
            ),
            SizedBox(height: 4.h),
            Text(
              '关注我赚更多',
              style: TextStyle(fontSize: 14.sp, color: Colors.grey),
            ),
          ],
        ),
      ],
    );
  }

  Widget _buildTaskStatusTags(TaskDetailModel model) {
    return Wrap(
      spacing: 8.w,
      runSpacing: 8.h,
      children: [
        _buildTag('雇主资金已托管', Icons.verified, Colors.blue),
        _buildTag(
          '每人仅可做${model.bidTimesByUser ?? 1}次',
          Icons.person_outline,
          Colors.green,
        ),
      ],
    );
  }

  Widget _buildTag(String text, IconData icon, Color color) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 6.h),
      decoration: BoxDecoration(
        color: color.withAlpha((255 * 0.1).round()),
        borderRadius: BorderRadius.circular(16.r),
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(icon, size: 16.w, color: color),
          SizedBox(width: 4.w),
          Text(
            text,
            style: TextStyle(fontSize: 12.sp, color: color),
          ),
        ],
      ),
    );
  }

  Widget _buildTaskDescription(TaskDetailModel model) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          '任务说明',
          style: TextStyle(fontSize: 18.sp, fontWeight: FontWeight.bold),
        ),
        SizedBox(height: 8.h),
        Text(
          model.taskDescription ?? '无任务说明',
          style: TextStyle(fontSize: 15.sp, height: 1.5),
        ),
      ],
    );
  }

  Widget _buildTaskSteps(TaskDetailModel model) {
    final steps = model.taskStepList as List? ?? [];

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          '任务步骤',
          style: TextStyle(fontSize: 18.sp, fontWeight: FontWeight.bold),
        ),
        SizedBox(height: 12.h),
        ...steps.asMap().entries.map((entry) => _buildStepItem(entry.value, entry.key + 1)).toList(),


      ],
    );
  }

  Widget _buildStepItem(TaskStep step, int index) {
    return Padding(
      padding: EdgeInsets.only(bottom: 16.h),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            width: 22.w,
            height: 22.w,
            decoration: BoxDecoration(
              shape: BoxShape.circle,
              border: Border.all(color: Theme.of(context).colorScheme.primary, width: 1.w),
            ),
            alignment: Alignment.center,
            child: Text(
              '$index',
              style: TextStyle(fontSize: 14.sp, color: Theme.of(context).colorScheme.primary),
            ),
          ),
          SizedBox(width: 8.w),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  step.taskDescription ?? '',
                  style: TextStyle(fontSize: 15.sp, height: 1.5),
                ),
                if (step.taskStepImages.isNotEmpty)
                  SizedBox(
                    height: 120.h,
                    child: ListView.builder(
                      scrollDirection: Axis.horizontal,
                      itemCount: step.taskStepImages.length,
                      itemBuilder: (context, imgIndex) {
                        return GestureDetector(
                          onTap: () {
                            _showImagePreview(context, step.taskStepImages, imgIndex);
                          },
                          child: Padding(
                            padding: EdgeInsets.only(top: 8.h, right: 8.w),
                            child: ClipRRect(
                              borderRadius: BorderRadius.circular(8.r),
                              child: CachedNetworkImage(
                                imageUrl: step.taskStepImages[imgIndex],
                                height: 120.h,
                                width: 120.h,
                                fit: BoxFit.cover,
                                errorWidget: (context, url, error) {
                                  return Image.asset(
                                    'assets/images/error_image_load.png',
                                    width: 120.h,
                                    height: 120.h,
                                    fit: BoxFit.cover,
                                  );
                                },
                              ),
                            ),
                          ),
                        );
                      },
                    ),
                  ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  void _showImagePreview(BuildContext context, List<String> images, int initialIndex) {
    showDialog(
      context: context,
      builder: (context) => Dialog(
        backgroundColor: Colors.transparent,
        insetPadding: EdgeInsets.zero,
        child: SizedBox(
          width: MediaQuery.of(context).size.width,
          height: MediaQuery.of(context).size.height * 0.8,
          child: PhotoViewGallery.builder(
            itemCount: images.length,
            builder: (context, index) {
              return PhotoViewGalleryPageOptions(
                imageProvider: CachedNetworkImageProvider(images[index]),
                minScale: PhotoViewComputedScale.contained,
                maxScale: PhotoViewComputedScale.covered * 2,
                initialScale: PhotoViewComputedScale.contained,
              );
            },
            backgroundDecoration: const BoxDecoration(color: Colors.black),
            pageController: PageController(initialPage: initialIndex),
            enableRotation: true,  // 允许旋转
            loadingBuilder: (context, event) => Center(
              child: CircularProgressIndicator(
                value: event == null ? 0 : event.cumulativeBytesLoaded / event.expectedTotalBytes!,
              ),
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildActionButton(TaskDetailModel model) {
    // 根据状态确定按钮样式和行为
    final (disabled, backgroundColor) = _getButtonStyle(model.taskStatus);
    return SizedBox(
      width: double.infinity,
      child: ElevatedButton(
        style: ElevatedButton.styleFrom(
          padding: EdgeInsets.symmetric(vertical: 16.h),
          backgroundColor: backgroundColor,
          shape: BeveledRectangleBorder()
          // shape: RoundedRectangleBorder(
          //   borderRadius: BorderRadius.circular(8.r),
          // ),
        ),
        onPressed: disabled ? null : () => _actionTask(context),
        child: Text(
          model.statusLabel ?? '领取任务',
          style: TextStyle(
            fontSize: 16.sp,
            color: Colors.white,
            fontWeight: FontWeight.bold,
          ),
        ),
      ),
    );
  }

  // 辅助方法：根据状态返回按钮样式
  (bool, Color) _getButtonStyle(String? statusLabel) {
    switch (statusLabel) {
      case '待领取':
        return (false, Theme.of(context).colorScheme.primary);
      case '待提交':
        return (false, Color.fromRGBO(75, 190, 151, 1));
      case '已拒绝':
        return (false, Color.fromRGBO(75, 190, 151, 1));
      default:
        return (true, Colors.grey);
    }
  }

  Widget _buildTaskRequirement(TaskDetailModel model) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          '需提交内容',
          style: TextStyle(fontSize: 18.sp, fontWeight: FontWeight.bold),
        ),
        SizedBox(height: 8.h),
        Text(
          model.taskRequirement,
          style: TextStyle(fontSize: 15.sp, height: 1.5),
        ),

        // 任务要求图片
        if (model.taskRequirementImages != null &&
            (model.taskRequirementImages as List).isNotEmpty)
          SizedBox(
            height: 120.h,
            child: ListView.builder(
              scrollDirection: Axis.horizontal,
              itemCount: (model.taskRequirementImages as List).length,
              itemBuilder: (context, imgIndex) {
                return GestureDetector(
                  onTap: () {
                    _showImagePreview(context, model.taskRequirementImages, imgIndex);
                  },
                  child: Padding(
                    padding: EdgeInsets.only(top: 8.h, right: 8.w),
                    child: ClipRRect(
                      borderRadius: BorderRadius.circular(8.r),
                      child: CachedNetworkImage(
                        imageUrl: model.taskRequirementImages[imgIndex],
                        height: 120.h,
                        width: 120.h,
                        fit: BoxFit.cover,
                        errorWidget: (context, url, error) {
                          return Image.asset(
                            'assets/images/error_image_load.png',
                            width: 120.h,
                            height: 120.h,
                            fit: BoxFit.cover,
                          );
                        },
                      ),
                    ),
                  ),
                );
              },
            ),
          ),
      ],
    );
  }
}
